<?php

namespace app\admin\controller;

use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\facade\Db;

/**
 * @ControllerAnnotation(title="车辆列表")
 */
class Vehicle extends AdminController
{

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Vehicle();
        
    }

     /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
                foreach ($list as $k => $v){
                    if(!empty($v['merchant_id'])){
                        $merchant = Db::name('merchant')->where('id',$v['merchant_id'])->field('merchant_name')->find();
                        if(!empty($merchant)){
                            $v['merchant_name'] = $merchant["merchant_name"];
                        }else{
                            $v['merchant_name'] = "";
                        }
                    }else{
                        $v['merchant_name'] = "";
                    }
                    
                    if(!empty($v['class_id'])){
                        $classification = Db::name('classification')->where('id',$v['class_id'])->field('title')->find();
                        if(!empty($classification)){
                            $v['class_name'] = $classification["title"];
                        }else{
                            $v['class_name'] = "";
                        }
                        $v['class_name'] = $classification["title"];
                    }else{
                        $v['class_name'] = "";
                    }
                    $list[$k] = $v;
                }
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

 
 
     /**
    * @NodeAnotation(title="编辑")
    */
    public function edit()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post['class_id'])){
                $this->error('车辆种类不能为空');
            }
            if(empty($post['spec_value'])){
                $this->error('分期估价不能为空');
            }
            $data = [
                'class_id'=>$post['class_id'],
                'titlt'=>$post['titlt'],
                'level'=>$post['level'],
                'power_type'=>$post['power_type'],
                'mileage'=>$post['mileage'],
                'registration_time'=>$post['registration_time'],
                'model'=>$post['model'],
                'equipped_withdisplacement'=>$post['equipped_withdisplacement'],
                'vehicle_color'=>$post['vehicle_color'],
                'vehicle_detection'=>$post['vehicle_detection'],
                'host_graphimg'=>$post['host_graphimg'],
                'real_shootingimg'=>$post['real_shootingimg'],

            ];
            if(!empty($post["status"]) && $post["status"] == 2){
                $data["status"] = 0;
                $data["reason"] = 0;
            }
            try {
               $this->model->where('id',$post['id'])->update($data);
               Db::name("vehicle_bystages")->where('vehicle_id',$post['id'])->delete();
               foreach($post["spec_value"] as $k=>$v){
                    $datasv = [
                        "vehicle_id"=>$post['id'],
                        "number_ofperiods"=>$v['number_ofperiods'],
                        "monthly_rentalamount"=>$v['monthly_rentalamount'],
                    ];
                    Db::name("vehicle_bystages")->insert($datasv);
               }
             
            } catch (\Exception $e) {
                //$e->getMessage()
                $this->error('保存失败手机号已存在');
            }
            $this->success('保存成功') ;
        }else{
            $post = $this->request->param(); 
            $row = $this->model->where('id',$post['id'])->find();
            $classarr = Db::name("classification")->order('id desc')->select()->toArray();
            $this->assign("classarr",$classarr); 
            if(!empty($row['merchant_id'])){
                $merchant = Db::name('merchant')->where('id',$row['merchant_id'])->field('merchant_name')->find();
                $row['merchant_name'] = $merchant["merchant_name"];
            }else{
                $row['merchant_name'] = "";
            }

            $vehicle_bystages = Db::name("vehicle_bystages")->where("vehicle_id",$post['id'])->order("id asc")->select()->toArray();
            $this->assign("vehicle_bystages",json_encode($vehicle_bystages)); 
            $this->assign('row', $row); 
            return $this->fetch();
        }
       
    }

    
    public function upload(){
        $file = $_FILES['file'];
     
        if (!isset($file['tmp_name']) || !$file['tmp_name']) {
            echo json_encode(array('code' => 401, 'msg' => '没有文件上传'));
            return false;
        }
        if ($file["error"] > 0) {
            echo json_encode(array('code' => 402, 'msg' => $file["error"]));
            return false;
        }
        $filename = time().rand(0, 1000);
        $ext = pathinfo($_FILES['file']['name'])['extension'];
        $filename = $filename . '.' . $ext;
        $upload_path = "resultfile/";
        
        $domain = ($this->isHTTPS() ? 'https://' : 'http://') . $_SERVER['HTTP_HOST']; //获取域名
        $save_path =$domain.'/' . $upload_path . $filename;
        if (!is_dir($upload_path)) {
            mkdir(iconv("UTF-8", "UTF-8", $upload_path), 0777, true);
        }
        if (move_uploaded_file($file["tmp_name"], $upload_path . $filename)) {
            echo json_encode(array('code' => 200, 'src' => $save_path));
        } else {
            echo json_encode(array('code' => 404, 'msg' => '上传失败'));
            return false;
        }
    }

    
    public function province(){
        if ($this->request->isAjax()) {
            $brand_id = $this->request->param('id');
            $list = Db::name("area")->where('pid', $brand_id)->select()->toArray();
            $opt = "<option value=''>--请选择--</option>";
            foreach ($list as $k => $val) {
                $opt .= "<option value='{$val['id']}'>{$val['name']}</option>";
            }
            if ($opt) {
                exit(json_encode(array('opt' => $opt)));
            } else {
                exit(json_encode(array('status' => 1)));
            }
        }
    }

    public function city(){
        if ($this->request->isAjax()) {
            $brand_id = $this->request->param('id');
            $list = Db::name("area")->where('pid', $brand_id)->select()->toArray();
            $opt = "<option value=''>--请选择--</option>";
            foreach ($list as $k => $val) {
                $opt .= "<option value='{$val['id']}'>{$val['name']}</option>";
            }
            if ($opt) {
                exit(json_encode(array('opt' => $opt)));
            } else {
                exit(json_encode(array('status' => 1)));
            }
        }
    }


    
    /**
    * @NodeAnotation(title="通过")
    */
    public function adopt_url()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            $ret = $this->model->where('id', $post['id'])->where('status', 0)->find();
            if (empty($ret)) {
                $this->error('当前车辆不可操作');
            }
            $this->model->where('id', $post['id'])->update(['status' =>1]);
        }
        $this->success('操作成功');
    }

  
    /**
    * @NodeAnotation(title="驳回")
    */
    public function reject_url()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->param();
            if(empty($post["reason_for_rejection"])){
                $this->error("驳回原因不能为空");
            }
            $this->model->where("id",$post["id"])->update(["status"=>2,"reason"=>$post["reason_for_rejection"]]);
            $this->success('驳回成功', '');
        }
        return $this->fetch();
    }

    
    

    
}